import React, { useEffect, useState } from 'react';
import { fetchPosts } from '../api';
import { useNavigate } from 'react-router-dom';

interface Post {
  id: number;
  title: string;
  content: string;
  createdAt: string;
  updatedAt: string;
  topicId: number;
  comments?: any[];
  _count?: { comments: number };
}

interface PostListProps {
  refreshFlag?: number;
  topicId: string;
}

const PostList: React.FC<PostListProps> = ({ refreshFlag, topicId }) => {
  const [posts, setPosts] = useState<Post[]>([]);
  const navigate = useNavigate();

  useEffect(() => {
    if (topicId) {
      fetchPosts(topicId).then(res => {
        let data = res.data;
        if (data && data.data) {
          setPosts(data.data);
        } else if (Array.isArray(data)) {
          setPosts(data);
        } else {
          setPosts([]);
        }
      });
    } else {
      setPosts([]);
    }
  }, [topicId, refreshFlag]);

  return (
    <div>
      <h3>动态</h3>
      <ul>
        {Array.isArray(posts) && posts.map(post => (
          <li key={post.id} onClick={() => navigate(`/topics/${post.topicId}/posts/${post.id}`)}>
            <div><b>{post.title}</b></div>
            <div>{post.content}</div>
            <div>评论数：{post._count && typeof post._count.comments === 'number' ? post._count.comments : (post.comments ? post.comments.length : 0)}</div>
          </li>
        ))}
        {posts.length === 0 && <li style={{ color: '#888', padding: 12 }}>暂无帖子</li>}
      </ul>
    </div>
  );
};

export default PostList;